package cn.com.blueInfo.bpm.common.response;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
public class EnumVO {

    private String enumClassName;          // 枚举类名
    private String enumClassSimpleName;    // 枚举类简单名称
    private List<EnumConstant> enumItems;      // 枚举项列表

    public EnumVO(Class<? extends Enum> enumClass) {
        this.enumClassName = enumClass.getName();
        this.enumClassSimpleName = enumClass.getSimpleName();
        this.enumItems = getEnumItems(enumClass);
    }

    /**
     * 获取枚举类的所有枚举项及其code和desc
     */
    private List<EnumConstant> getEnumItems(Class<? extends Enum> enumClass) {
        List<EnumConstant> items = new ArrayList<>();

        try {
            // 获取枚举常量
            Enum[] enumConstants = enumClass.getEnumConstants();
            // 获取code和desc字段
            Field codeField = enumClass.getDeclaredField("code");
            Field descField = enumClass.getDeclaredField("desc");

            // 设置字段可访问（即使是private）
            codeField.setAccessible(true);
            descField.setAccessible(true);

            // 遍历所有枚举常量，获取code和desc值
            for (Enum enumConstant : enumConstants) {
                Object code = codeField.get(enumConstant);
                Object desc = descField.get(enumConstant);

                items.add(new EnumConstant(
                        enumConstant.name(),
                        code,
                        desc.toString()
                ));
            }
        } catch (Exception e) {
            throw new RuntimeException("解析枚举类" + enumClass.getName() + "失败", e);
        }

        return items;
    }

    /**
     * 枚举常量信息
     */
    @Data
    @AllArgsConstructor
    public static class EnumConstant {

        private String name;
        // 常量名称
        private Object code;
        // 常量值(toString())
        private String desc;
    }

}
